import { Fragment, useContext, useState } from 'react';
import { WorkflowCheckRecordContext } from '../common';
import _ from 'lodash';
import { Button, Empty, Space, Timeline } from 'antd';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import { WorkflowNodeEnd } from './WorkflowNodeEnd';
import { WorkflowHandledListView } from './WorkflowHandledListView';
import { WorkflowNotHandView } from './WorkflowNotHandView';
import { WorkFlowCheckDrawer } from './WorkFlowCheckDrawer';
import { CloseCircleOutlined, CheckCircleOutlined } from '@ant-design/icons';

export const WorkflowTimeListView: React.FC<IWorkflowChedkRecordAPI.IWorkflowTimeListView> = ({ taskNodeInfoObj }) => {
  const { prefixCls, isCheckDrawer } = useContext(WorkflowCheckRecordContext);

  /** 是否打开办理抽屉 */
  const [isShowCheckDrawer, setIsShowCheckDrawer] = useState<Record<string, any>>({
    isShow: false,
    resObj: null
  });

  // /**
  //  * 处理拼接发起时间和任务名称
  //  * @param nodeList 任务节点数据
  //  * @returns
  //  */
  // const splicNameTime = (nodeList: any[]) => {
  //   let newNodelist: Record<string, any>[] = [];
  //   nodeList?.forEach((item: any) => {
  //     if (item?.assigneeID) {
  //       let newObj: Record<string, any> = {
  //         ...item,
  //         taskNameAndStartTime: item?.taskName + '&&' + item?.startTime,
  //       };
  //       newNodelist?.push(newObj);
  //     }
  //   });
  //   return newNodelist;
  // };

  // /**
  //  * 合并每个任务下的数据
  //  * @param nodeObj  已经分类后的数据,
  //  * @returns
  //  */
  // const mergeParamsObjNode = (nodeObj: Record<string, any>) => {
  //   let nodeList: Record<string, any>[] = [];

  //   for (let objItem in nodeObj) {
  //     const [taskName, startTime] = objItem?.split('&&');

  //     let newObjItemList: Record<string, any> = ([] = _.cloneDeep(
  //       nodeObj?.[objItem],
  //     ));
  //     /**
  //      * 通过结束时间时间进行降序排序
  //      */
  //     newObjItemList?.sort((itemA: any, itemB: any) => {
  //       let endTimeA = itemA?.endTime ? moment(itemA?.endTime)?.valueOf() : 0;
  //       let endTimeB = itemA?.endTime ? moment(itemB?.endTime)?.valueOf() : 0;
  //       return endTimeB - endTimeA;
  //     });
  //     let taskObj: Record<string, any> = {
  //       taskName,
  //       startTime,
  //       handUserList: newObjItemList,
  //       id: `${getKeyRouter()}${getKeyRouter()}`,
  //     };
  //     nodeList?.push(taskObj);
  //   }

  //   /** 拷贝一份数据,用于排序  */
  //   let sortNodeList: Record<string, any>[] = _.cloneDeep(nodeList);

  //   /** 通过开始时间进行降序排序 */
  //   sortNodeList?.sort((itemA: any, itemB: any) => {
  //     let startTimeA = itemA?.startTime
  //       ? moment(itemA?.startTime)?.valueOf()
  //       : 0;
  //     let startTimeB = itemB?.startTime
  //       ? moment(itemB?.startTime)?.valueOf()
  //       : 0;
  //     return startTimeB - startTimeA;
  //   });
  //   return sortNodeList;
  // };

  // /**
  //  * 处理流程已办理或正在办理数据,分类
  //  * @param nodeHandList 任务节点数据
  //  * @returns
  //  */
  // const pastHandTaskListMemo = (nodeHandList: any[]) => {
  //   let pastHandList: Record<string, any> = [];
  //   let paramsObj: Record<string, any> | any = {};

  //   if (nodeHandList && nodeHandList?.length > 0) {
  //     let nameAndTimeList: Record<string, any>[] = splicNameTime(nodeHandList); //处理合并 任务名称和 开始时间

  //     nameAndTimeList?.forEach((item: any) => {
  //       /**按照相同 任务相同开始时间合并数据 */
  //       if (paramsObj[item?.taskNameAndStartTime] && paramsObj[item?.taskNameAndStartTime]?.length > 0) {
  //         let newList: any[] = _.cloneDeep(
  //           paramsObj[item?.taskNameAndStartTime],
  //         );
  //         newList?.push(item);
  //         paramsObj[item?.taskNameAndStartTime] = newList;
  //       } else {
  //         paramsObj[item?.taskNameAndStartTime] = [item];
  //       }
  //     });
  //   }

  //   if (paramsObj && JSON.stringify(paramsObj) != '{}') {
  //     pastHandList = mergeParamsObjNode(paramsObj);
  //   }
  //   return pastHandList;
  // };

  // /**
  //  *  处理节点间用户数据
  //  * @param dealerKey 岗位 & 用户 id
  //  * @param dealerName 岗位 & 用户 name
  //  * @returns
  //  */
  // const handNodeUserList = (dealerKey: string[], dealerName: string[]) => {
  //   let allList: Record<string, any>[] = [];
  //   dealerKey?.forEach((itemKey: any, index: number) => {
  //     let [postKey, userKey] = itemKey?.split('|');
  //     let [postName, userName] = dealerName?.[index]?.split('|');
  //     let obj = {
  //       postKey,
  //       postName,
  //       userKey,
  //       userName,
  //     };
  //     allList?.push(obj);
  //   });
  //   return allList;
  // };

  // /**
  //  * 处理流程未办理任务数据
  //  */
  // const notHandTaskListMemo = useMemo(() => {
  //   let notHandList: Record<string, any>[] = [];
  //   if (
  //     taskNodeInfoObj?.activitiTaskHandleList &&
  //     taskNodeInfoObj?.activitiTaskHandleList?.length > 0
  //   ) {
  //     taskNodeInfoObj?.activitiTaskHandleList?.forEach((itemNot: any) => {
  //       /**
  //        * 获取到处理人的数据
  //        */
  //       let userListKey: string[] = itemNot?.postDealerID ? itemNot?.postDealerID?.split(',')?.filter((itemUserKey: any) => itemUserKey) : [];
  //       let userListName: string[] = itemNot?.postDealerName ? itemNot?.postDealerName?.split(',')?.filter((itemUserName: any) => itemUserName) : [];

  //       let newUserList = handNodeUserList(userListKey, userListName);

  //       let notItemObj: Record<string, any> = {
  //         ...itemNot,
  //         handleUserList: newUserList,
  //       };
  //       notHandList?.push(notItemObj);
  //     });
  //   }
  //   return notHandList;
  // }, [taskNodeInfoObj?.activitiTaskHandleList]);

  /**
   * 排序
   * @param arr
   * @returns
   */
  const sortNodeTaskArr = (nodeArr: Record<string, any>[]) => {
    if (nodeArr && nodeArr?.length > 0) {
      let durArrStart: Record<string, any>[] = [];
      let durArrEnd: Record<string, any>[] = [];
      nodeArr?.forEach((item: any) => {
        if (item?.duration == 0) {
          durArrStart.push(item);
        } else {
          durArrEnd?.push(item);
        }
      });
      return durArrStart.concat(durArrEnd);
    } else {
      return [];
    }
  };

  /**
   * 处理是否流程结束节点
   * @param nodeItem 流程节点 数据
   * @returns
   */
  const handleFlowEndNodes = (nodeItem: Record<string, any>) => {
    let itemChildTaskList: any = [];
    // 流程信息-判断endtime是否有值-有在时间节点上展示
    const endTaskName: Record<string, any> = {
      ...nodeItem,
      nodeState: 'endState',
      mactivitiHisTaskInstList: '',
    };
    const processInformation = nodeItem?.endTime ? [endTaskName] : [];

    if (nodeItem?.mactivitiHisTaskInstList && nodeItem?.mactivitiHisTaskInstList?.length > 0) {
      itemChildTaskList = sortNodeTaskArr(nodeItem?.mactivitiHisTaskInstList);
    }
    const activitiHisTaskInstList: any = nodeItem.mactivitiHisTaskInstList ? processInformation?.concat(itemChildTaskList) : [];

    return activitiHisTaskInstList;
  };

  return (
    <div className={`${prefixCls}flowCheckDomBox`}>
      {(taskNodeInfoObj?.activitiTaskHandleList && taskNodeInfoObj?.activitiTaskHandleList?.length > 0) ||
        (taskNodeInfoObj?.activitiHisProcinstList && taskNodeInfoObj?.activitiHisProcinstList?.length > 0) ? (
        <>
          <div className={`${prefixCls}flowCheckDomBox-flowListDiv`}>
            <ScrollBarLayout>
              <Timeline className={prefixCls + 'flowCheckTimeBox'}>
                {/* 未办理任务节点 */}
                {taskNodeInfoObj?.activitiTaskHandleList && taskNodeInfoObj?.activitiTaskHandleList?.length > 0 && (
                  <WorkflowNotHandView notHandTaskListMemo={taskNodeInfoObj?.activitiTaskHandleList} />
                )}

                {/* 已办理任务节点 */}
                {taskNodeInfoObj?.activitiHisProcinstList && taskNodeInfoObj?.activitiHisProcinstList?.length > 0 && (
                  <>
                    {taskNodeInfoObj?.activitiHisProcinstList?.map((pItem: Record<string, any>) => {
                      const flowNodeTaskList: Record<string, any>[] = handleFlowEndNodes(pItem);
                      return flowNodeTaskList?.map((cItem: Record<string, any>, cIndex: any) => {
                        if (cItem?.nodeState == 'endState') {
                          return <WorkflowNodeEnd key={`${cItem?.id}TimeFlow${cIndex}`} taskNodeInfo={cItem} />;
                        } else if (cItem?.assigneeName) {
                          return <WorkflowHandledListView key={`${cItem?.id}TimeFlow${cIndex}`} taskNodeInfo={cItem} />;
                        } else {
                          return <Fragment key={`${cItem?.id}TimeFlow${cIndex}`} />;
                        }
                      });
                    })}
                  </>
                )}
              </Timeline>
            </ScrollBarLayout>
          </div>
          {/* {
            isCheckDrawer &&
            <>
              <div className={`${prefixCls}flowCheckDomBox-checkDrawerBtn`}>
                <Space>
                  <Button
                    // type={'primary'}
                    type="primary"
                    danger
                    icon={<CloseCircleOutlined />}
                    onClick={() => {
                      setIsShowCheckDrawer({
                        isShow: true,
                        resObj: 'false'
                      });
                    }}
                  >
                    不同意
                  </Button>
                  <Button
                    type={'primary'}
                    icon={<CheckCircleOutlined />}
                    onClick={() => {
                      setIsShowCheckDrawer({
                        isShow: true,
                        resObj: 'true'
                      });
                    }}
                  >
                    同意
                  </Button>
                </Space>
              </div>
            </>
          } */}
        </>
      ) : (
        <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无审批记录！" />
      )}

      {/* 办理流程抽屉 */}
      <WorkFlowCheckDrawer
        isShowDrawer={isShowCheckDrawer}
        onClose={() => {
          setIsShowCheckDrawer({
            isShow: false,
            resObj: null
          });
        }}
      />
    </div>
  );
};
